package com.learning.spring.data.transaction.advance.propagation.service.impl;

import com.learning.spring.data.transaction.advance.propagation.entity.Address;
import com.learning.spring.data.transaction.advance.propagation.entity.User;
import com.learning.spring.data.transaction.advance.propagation.service.IAddressService;
import com.learning.spring.data.transaction.advance.propagation.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ClassName: UserServiceImpl
 * Description:
 * Date: 2020/7/22 16:19 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Transactional(rollbackFor = Exception.class,
        isolation = Isolation.DEFAULT,
        propagation = Propagation.REQUIRED)
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IAddressService addressService;

    /**
     * 事务方法嵌套调用：
     * 事务执行的开始是被环绕增强拦截的方法：
     * TransactionInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
     *
     * @param user
     * @return
     */
    @Override
    public int add(User user) {
        System.out.println("~~~ Before IUserService.update method ~~~");
        // 本服务类的其他方法
        update(user);
        System.out.println("*** After IUserService.update method ***");


        System.out.println("~~~ Before IAddressService.add method ~~~");
        // 其他服务类的方法其他服务类的方法
        addressService.add(new Address());
        System.out.println("*** After IAddressService.add method ***");
        return 1;
    }


    /**
     * JDBC 模板操作数据
     *
     * @param id
     * @return
     */
    @Override
    public int delete(int id) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.execute(new StatementCallback() {
            @Override
            public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
                // 执行业务数据操作
                ResultSet resultSet = stmt.executeQuery("SELECT * FROM t_user WHERE ?");
                return null;
            }
        });

        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Transactional(rollbackFor = Exception.class,
            isolation = Isolation.DEFAULT,
            propagation = Propagation.REQUIRED,
            readOnly = true, timeout = 10000)
    @Override
    public User select(int id) {
        return null;
    }
}
